package com.infore.airsupervise.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

import com.infore.airsupervise.R;
import com.infore.airsupervise.service.inter.ProcessConnection;

/**
 * 子服务
 * <p>
 * 作者: dingxinlin
 * 创建日期: 2017/4/22 14:12
 */

public class SubService extends Service {

    private SubBinder subBinder;
    private MainServiceConnection mainConn;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return subBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (subBinder == null) {
            subBinder = new SubBinder();
        }
        mainConn = new MainServiceConnection();
    }

    /**
     * 服务被启动
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 绑定主服务
        this.bindService(new Intent(this, MainService.class), mainConn, Context.BIND_IMPORTANT);

        // 启动时在通知栏展示通知，以提升优先级
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.wg_icon)
                .setContentTitle("大气趋势化")
                .setContentText("持续为您提供服务");
        // 前台运行，避免休眠被杀死
        startForeground(1, builder.build());

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindService(mainConn);
    }


    /**
     * Sub Binder
     */
    private class SubBinder extends ProcessConnection.Stub {

        @Override
        public void getProcessName() throws RemoteException {
//            Log.i("DXL", "getProcessName：Sub Service");
        }
    }

    /**
     * 连接主服务的回调
     */
    private class MainServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            Log.i("DXL", "主服务连接成功");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 表示子服务被杀死
//            Log.i("DXL", "主服务被杀死");
            // 这时先启动子服务
            SubService.this.startService(new Intent(SubService.this, MainService.class));
            // 再绑定子服务
            SubService.this.bindService(
                    new Intent(SubService.this, MainService.class), mainConn, Context.BIND_IMPORTANT);
        }
    }
}
